package com.sxzbxc.weixin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sxzbxc.weixin.entity.SysUser;
import com.sxzbxc.weixin.pojo.AjaxJson;
import com.sxzbxc.weixin.service.SysUserServiceI;

@Controller
@RequestMapping("/loginController")
public class LoginController {

	
	@Autowired
    private SysUserServiceI userService;
	/**
	 * 用户登录
	 * @return
	 */
	@RequestMapping(params = "toLogin")
	public ModelAndView toLogin(){
		//方式一：接收微信号来实现免登录
		//方式二：通过账号密码登录
		
		return new ModelAndView("login/login-info");
	}
	
	/**
	 * 检查登录信息
	 * @param userName
	 * @param password
	 * @return
	 */
	@RequestMapping(params = "checkLogin")
	@ResponseBody
	public AjaxJson checkLogin( HttpServletRequest request , String userName , String password){
		AjaxJson j = new AjaxJson();
		SysUser checkLogin = userService.checkLogin(userName, password);
		if(checkLogin!=null){
			if(checkLogin.getUserStatus1()==0){
				j.setSuccess(false);
				j.setMsg("该用户未激活");
				j.setSuccess(false);
			}else{
				saveLoginSuccessInfo(request , checkLogin);
				j.setSuccess(true);
			}
		}else{
			j.setMsg("此用户为空或密码不正确");
			j.setSuccess(false);
		}
		return j;
	}
	
	
	@RequestMapping(params = "login")
	public ModelAndView login(HttpServletRequest req){
		//SysUser user = (SysUser)req.getSession().getAttribute("user");
		return new ModelAndView("login/login-main");
	}
	
	/**
	 * 保存登录信息
	 * @param request
	 * @param user
	 */
	public void saveLoginSuccessInfo(HttpServletRequest request , SysUser user){
		HttpSession session = request.getSession();
		session.setAttribute("user", user);
	}
	
	/**
	 * 获取用户名
	 * @param request
	 * @param user
	 */
	@RequestMapping(params = "getUserName")
	@ResponseBody
	public AjaxJson getUserName(HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		SysUser user = (SysUser)request.getSession().getAttribute("user");
		j.setObj(user);
		j.setSuccess(true);
		return j;
	}
	
}
